import logging
import time
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError

from app.api import api_router
from app.core.exception_handler import ExceptionHandler
from app.core.config import settings
from app.core.logging import setup_logging
from app.core.middleware import ApiRequestLogger
from app.database.database import engine, Base
from app.exception import CodeException

# python start.py --env dev --port 8080
# 记录开始时间
start_time = time.time()

# 设置日志（会覆盖basicConfig的设置，但保留其配置）
setup_logging()
logger = logging.getLogger(__name__)
logger.info("Application starting...")

try:
    # 创建数据库表
    Base.metadata.create_all(bind=engine)
    logger.info("Database tables created/verified")
except Exception as e:
    logger.error(f"Failed to create/verify database tables: {e}")
    raise RuntimeError(f"Database initialization failed: {e}") from e

# 使用属性访问方式获取配置
app_config = settings.app_config
swagger_config = settings.swagger_config
interceptor_config = settings.interceptor_config

# 创建FastAPI应用
app = FastAPI(
    title=swagger_config.title,
    description=swagger_config.description,
    version=app_config.version,
    # 根据环境动态设置调试模式，生产环境禁用调试模式
    debug=not settings.is_prod(),
    # 禁用OpenAPI文档的reDoc，简化生产环境
    redoc_url=None if settings.is_prod() else "/redoc",
    # 生产环境禁用API自动生成的JSON Schema
    openapi_url=None if settings.is_prod() else "/openapi.json"
)

# 添加CORS中间件
# 根据环境配置CORS，生产环境使用配置的域名列表
cors_origins = interceptor_config.response.allowed_origins if hasattr(interceptor_config, 'response') else ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
logger.info("CORS middleware added")

# 添加API请求日志中间件，专门拦截/api/*请求
app.add_middleware(ApiRequestLogger)
logger.info(f"API request logger middleware added for /api/* paths, whitelist: {interceptor_config.whitelist}")

# 注册API路由，添加/api前缀
app.include_router(api_router)
logger.info("API routes registered with /api prefix")

# 注册异常处理器，使用类.方法的引用方式
app.add_exception_handler(RequestValidationError, ExceptionHandler.validation_exception_handler)
app.add_exception_handler(HTTPException, ExceptionHandler.http_exception_handler)
app.add_exception_handler(CodeException, ExceptionHandler.code_exception_handler)
app.add_exception_handler(Exception, ExceptionHandler.global_exception_handler)
logger.info("Exception handlers registered.")

# 添加健康检查端点
@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": app_config.version}

logger.info(f"Application startup complete, listening on port {app_config.port}, startup cost time: {int((time.time() - start_time) * 1000)}ms")